package com.link510.nbiot.cmcc.invokeapi;

import com.alibaba.fastjson.JSON;
import com.link510.nbiot.cmcc.NBIoTClient;
import com.link510.nbiot.cmcc.domain.OnenetMessageInfo;
import com.link510.nbiot.cmcc.domain.commands.CacheCommandOutDTO;
import com.link510.nbiot.cmcc.domain.commands.SendCommandDTO;
import com.link510.nbiot.cmcc.exption.NBStatus;
import com.link510.nbiot.cmcc.exption.OnenetNBException;

public class CommandManagement extends BaseManagement {

    private NBIoTClient nbIoTClient;

    private CommandManagement() {

    }

    public CommandManagement(NBIoTClient nbIoTClient) {
        this.nbIoTClient = nbIoTClient;
    }

    /**
     * 发送及时命令
     *
     * @param commandDTO 命令
     * @return
     */
    public CacheCommandOutDTO sendCommand(SendCommandDTO commandDTO) throws OnenetNBException {

        try {

            OnenetMessageInfo messageInfo = this.nbIoTClient.restJsonPost(commandDTO.toUrl(), commandDTO.toJson(), OnenetMessageInfo.class);

            validateMessageInfo(messageInfo);

            return JSON.parseObject(messageInfo.getData(), CacheCommandOutDTO.class);

        } catch (OnenetNBException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new OnenetNBException(NBStatus.PARSER_DATA_ERROR, "数据解析异常");
        }
    }



    public CacheCommandOutDTO sendBinaryCommand(SendCommandDTO commandDTO) throws OnenetNBException {
        try {

            OnenetMessageInfo messageInfo = this.nbIoTClient.restBinaryPost(commandDTO.toUrl(), commandDTO.toJson(), OnenetMessageInfo.class);

            validateMessageInfo(messageInfo);

            return JSON.parseObject(messageInfo.getData(), CacheCommandOutDTO.class);

        } catch (OnenetNBException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new OnenetNBException(NBStatus.PARSER_DATA_ERROR, "数据解析异常");
        }
    }


}
